<script setup lang="ts">
import type {SysDept} from "@/api/dept/types.ts";
import {deptApi} from "@/api/dept";
import {NSpace, NTag, NText, TreeOption} from "naive-ui";
import {useRoute, useRouter} from "vue-router";

const router = useRouter();
const currentRoute = useRoute();
const treeLoading = ref(false)
const treeData = ref<SysDept[]>([])
const treeFilteredData = ref<SysDept[]>([])
const treeSelectedKeys = ref<string[]>([])
const treeDefaultExpandedKeys = ref<string[]>([])
const treeKeyword = ref('')

onMounted(() => {
  const deptId = currentRoute.query.deptId;
  if (deptId) {
    treeSelectedKeys.value = [deptId as string]
  }
  handleClickTree()
})

watch(() => treeKeyword.value, (keyword) => {
  if (keyword) {
    treeFilteredData.value = treeData.value.filter(item => item.deptName.includes(keyword) || item.deptCode.includes(keyword))
  } else {
    treeFilteredData.value = treeData.value
  }
})

const renderTreeLabel = ({option}: { option: TreeOption }) => {
  return h(NSpace, {}, {
    default: () => [
      h(NText, {type: 'primary'}, {default: () => option.deptName}),
      h(NTag, {size: 'small', type: 'info'}, {default: () => option.deptCode})
    ]
  })
}
const handleClickTree = () => {
  treeLoading.value = true
  deptApi.tree().then(res => {
    treeData.value = res.data
    treeFilteredData.value = res.data
    treeDefaultExpandedKeys.value = res.data.map(item => item.id)
  }).finally(() => treeLoading.value = false)
}
const handleChangeSelectedKey = (keys: string[]) => {
  treeSelectedKeys.value = keys
  let query = currentRoute.query;
  router.replace({query: {...query, deptId: keys[0]}})
}
</script>

<template>
  <n-card w-300px h-fit>
    <template #header>
      <n-input-group>
        <n-button @click="handleClickTree">
          <template #icon>
            <n-icon size="22">
              <icon-lucide:list-restart/>
            </n-icon>
          </template>
        </n-button>
        <n-input v-model:value="treeKeyword" placeholder="请输入部门名称/部门编码" clearable/>
      </n-input-group>
    </template>
    <n-spin :show="treeLoading">
      <n-tree
          block-line
          :key-field="'id'"
          :selected-keys="treeSelectedKeys"
          :data="treeFilteredData"
          :default-expanded-keys="treeDefaultExpandedKeys"
          :render-label="renderTreeLabel"
          @update:selected-keys="handleChangeSelectedKey"
      />
    </n-spin>
  </n-card>
</template>

<style scoped>

</style>